package cn.pengpeng.day04.flowcount;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;


public class FlowCount {
	public static class MapTask extends Mapper<LongWritable, Text, Text, FlowBean>{
		
		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, FlowBean>.Context context)
				throws IOException, InterruptedException {
			//18494845774	http://www.edu360.cn 17164 12376
			String line = value.toString();
			String[] split = line.split("\t");
			String pNum = split[0].substring(0, 3);
			String[] split2 = split[1].split(" ");
			long up = Long.parseLong(split2[1]);
			long down = Long.parseLong(split2[2]);
			FlowBean flowBean = new FlowBean();
			flowBean.set(up, down);
			context.write(new Text(pNum), flowBean);
		}
	}
	
	public static class ReduceTask extends Reducer<Text, FlowBean, Text, FlowBean>{
		FlowBean flowBean = new FlowBean();
		@Override
		protected void reduce(Text arg0, Iterable<FlowBean> arg1, Reducer<Text, FlowBean, Text, FlowBean>.Context arg2)
				throws IOException, InterruptedException {
			long sumUp = 0;
			long sumDown = 0;
			for (FlowBean flowBean : arg1) {
				sumUp+=flowBean.getUp();
				sumDown+=flowBean.getDown();
			}
			
			flowBean.set(sumUp, sumDown);
			arg2.write(arg0, flowBean);
		}
	}
	
	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);
		
		//设置job的map 和 reduce 是哪一个 提交任务的类
		job.setMapperClass(MapTask.class);
		job.setReducerClass(ReduceTask.class);
		job.setJarByClass(FlowCount.class);
		
		//设置输出的类型
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(FlowBean.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(FlowBean.class);
		
		job.setNumReduceTasks(2);
		//设置输入目录和输出目录
		FileInputFormat.addInputPath(job, new Path("d:/data/http.log"));
		FileOutputFormat.setOutputPath(job, new Path("d:/out/Flowoutput"));
		
		
		File file = new File("d:/out/Flowoutput");
		if(file.exists()){
			FileUtils.deleteDirectory(file);
		}
		
		//提交任务并等待任务结束，能够打印日志
		boolean waitForCompletion = job.waitForCompletion(true);
		System.out.println(waitForCompletion?"程序正常退出":"程序有问题了");
	}

}
